package com.cola.colaboot.module.system.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.cola.colaboot.config.dto.Res;
import com.cola.colaboot.config.exception.ColaException;
import com.cola.colaboot.utils.FastDFSClientUtil;
import com.cola.colaboot.utils.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping("/file")
public class SysFileController {

    @Autowired
    private FastDFSClientUtil fastDFSClientUtil;

    @Value("${tracker_server}")
    private String trackerServer;

    public static final String FILE_ROOT_URL = "/opt/upload/file/";
    public static Map<String, Integer> fileSizeLimit = new HashMap<>();//文件夹上传大小限制，

    static {
        fileSizeLimit.put("imgPool", 10);
    }


    /**
     * 文件上传
     *
     * @param dir 文件夹名
     */
    @PostMapping("/upload")
    public Res<?> upload(@RequestParam("file") MultipartFile multipartFile,
                         @RequestParam("dir") String dir, @RequestParam(value = "fileName", required = false) String fileName) {
        if (StringUtils.isBlank(dir)) {
            throw new ColaException("文件夹名不能为空");
        }
        Integer sizeLimit = fileSizeLimit.get(dir);
        if (multipartFile.getSize() > Objects.requireNonNullElse(sizeLimit, 10) * 1024 * 1024) {
            throw new ColaException("文件过大");
        }
//        File file = FileUtil.saveFile(FILE_ROOT_URL + dir, fileName, multipartFile);
//        return Res.ok("success","/"+dir+"/"+file.getName());
        // 文件上传到文件服务器
        try {
            // 获得文件地址
            String fileUrl = fastDFSClientUtil.uploadFile(multipartFile);
            return Res.ok("success", trackerServer + fileUrl);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
